package org.deng.learn.netty.barrage;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 邓力宾
 * @Desc 弹幕服务器
 * @since 2020/6/16 下午3:23
 */
public class BarrageServer {

    private int port;
    public BarrageServer(int port){
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(2); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebsocketBarrageServerInitializer())
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture future = bootstrap.bind(this.port).sync();
            System.out.println("弹幕服务器已启动");
            //等待服务器  socket 关闭
            // 在这个例子中，这不会发生，但你可以优雅地关闭你的服务器
            future.channel().closeFuture().sync();

        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            System.out.println("服务器已关闭");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new BarrageServer(8010).start();
    }
}
